<template>
  <el-upload
    ref="uploadFile"
    class="avatar-uploader"
    accept="image/png, image/jpg, image/jpeg, image/gif"
    :http-request="uploadImg"
    action="#"
    :before-upload="beforeUploadImg"
    :on-preview="onUploadPreviewImg"
    :on-remove="handleRemoveImg"
    :on-success="onUploadImgSuccessImg"
    :on-change="handleChangeImg"
    :on-error="handleOnUplodeImgErrorImg"
    :show-file-list="false"
    :limit="2"
    :on-exceed="handleExceed"
  >
    <img v-if="imageUrl" class="avatar" :src="imageUrl">
    <svg-icon v-else icon-class="user-avatar" class="avatar" />
  </el-upload>
</template>

<script>
// 附件上传
import { fileDownLoad } from '@/api/file/file.js'
import { fileUpload } from '@/api/common/upload'
import { imgDownLoad } from '@/api/common/upload.js'
import { updateAvatar, removeAvatar } from '@/api/system/profile'
export default {
  name: 'UploadAvatar',
  props: {
    avatarFiles: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      fileList: [],
      fileIdsList: [],
      imageUrl: ''
    }
  },
  watch: {
    avatarFiles(newVal, oldVal) {
      newVal && this.imgDownLoad(newVal)
    }
  },
  methods: {
    // 自定义文件上传
    uploadImg(item) {
      const formData = new FormData()
      formData.append('file', item.file)
      // const uid = item.file.uid
      fileUpload(formData, 'userProfile')
        .then((res) => {
          item.onSuccess(res)
        })
        .catch(({ err }) => {
          item.onError(err)
        })
    },
    beforeUploadImg(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isGIF = file.type === 'image/gif'
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isJPG && !isPNG && !isGIF) {
        this.$message.error('上传图片只能是 JPG、PNG 或 GIF 格式!')
        return false
      }
      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过 5MB!')
        return false
      }
      return true
    },
    // 上传的文件预览
    onUploadPreviewImg(file) {
      const fileId = file.fileId
      const fileName = file.name
      fileDownLoad(fileId).then((res) => {
        // 文件流下载
        this.downloadFileFlow(res, fileName)
      })
    },
    // 文件删除
    handleRemoveImg(file, fileList) {
      // eslint-disable-next-line no-prototype-builtins
      const isRe = file.hasOwnProperty('response')
      let fileId = null
      if (isRe) {
        fileId = file.response.data.fileId
      } else {
        fileId = file.fileId
      }
      if (!fileId) return
      this.deleteById(fileId)
      for (let j = 0; j < this.fileIdsList.length; j++) {
        if (fileId === this.fileIdsList[j].fileId) {
          // 删除存放附件id数组中的id
          this.fileIdsList.splice(j, 1)
        }
      }
      this.imageUrl = ''
    },
    // 图片上传失败的回调
    handleOnUplodeImgErrorImg(err, file, fileList) {
      if (err.message === 'Network Error') {
        this.$message.error('上传文件过大，重新上传')
      } else {
        this.$message.error('上传失败，请重新上传')
      }
      this.$refs.uploadImg.clearFiles()
    },
    // 上传图片成功的回调
    onUploadImgSuccessImg(res, file) {
      if (this.fileIdsList.length) {
        this.deleteById(this.fileIdsList[0].fileId)
        this.fileList.splice(
          this.fileList.findIndex((item) => item.fileId === fileId),
          1
        )
      }
      const { fileId, fileName, url } = res.data
      const uid = file.uid
      const fileData = { fileId, fileName, url, uid }
      this.imageUrl = URL.createObjectURL(file.raw)
      // 填充上传文件列表
      console.log(111)
      updateAvatar({ profilePortrait: fileId }).then((res) => {
        this.$store.commit('user/SET_AVATAR', fileId)
      })
      this.fileIdsList = []
      this.fileIdsList.push(fileData)
    },
    imgDownLoad(id) {
      const data = { id }
      imgDownLoad(data).then(res => {
        // 将从后台获取的图片流进行转换
        this.imageUrl = 'data:image/png;base64,' + btoa(new Uint8Array(res).reduce((data, byte) => data + String.fromCharCode(byte), ''))
        this.$store.commit('user/SET_AVATAR', id)
      })
    },
    // 编辑页面已经存到表中的附件
    deleteById(fileId) {
      removeAvatar(fileId)
    },
    // 限制文件上传的个数
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 2 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      )
    },
    handleChangeImg(file, fileList) {
      this.fileList = fileList
    }
  }
}
</script>

<style lang='scss' scoped>
  @import '@/styles/variables.scss';
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: $blue;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px!important;
  height: 178px!important;
  display: block;
  border-radius: 50%;
}
.add-icon {
  cursor: pointer;
  font-size: 20px;
  vertical-align: middle;
  color: $blue;
}
</style>
